var mongodb = require('mongodb');
let mongoCt = mongodb.MongoClient;
let ObjectId = mongodb.ObjectId;// 对象型的_id
let sql = 'lxn';//默认库名

require('mongodb').MongoClient.connect
//链接库
let open = ({dbName=sql, collectionName,url = 'mongodb://127.0.0.1:27017'})=>{
  return new Promise((resolve,reject)=>{

    if(!collectionName) {
      reject('集合名为空');
      return;
    }

    mongoCt.connect('mongodb://localhost:27017',(err,client)=>{
      //err 错误 client链接后的客户端
      if(err){
        reject({err,client})
      }else{
        let db = client.db(dbName);// db 链接后的库   
        let collection = db.collection(collectionName);
        console.log(collection)
        resolve({collection,client})
      }

    })

  })
}

//列表
let findList = ({
  collectionName,
  dbName=sql,
  _page,_limit,_sort,q
}) => new Promise((resolve,reject)=>{
  //链库
  open({
    dbName,collectionName
  }).then(
    ({collection,client})=>{

      // let rule = {title:/苏/};
      // let rule = q ? {title: new RegExp(q,'g')} : {}
      let rule = q ? {title: eval('/' + q + '/')} : {}

      //查列表
      collection.find(rule,{
        skip: _page * _limit,
        limit: _limit,
        // projection:{_id:0,age:1},
        sort:{[_sort]:-1}
      }).toArray((err,result)=>{
        if(!err && result.length>0){
          resolve({
            err:0,
            msg:'成功',
            data: result
            
          })
        }else{
          resolve({
            err:0,
            msg:'没有跟多数据'
          })
        }
        client.close();//管库
      })
    }
  ).catch(
    ({err,client}) => {
      reject({
        err:1,
        msg:'库链接失败'
      });
      client.close()
    }
  )
})

//详情
let findDetail = ({
  collectionName,
  dbName = sql,
  _id = null
}) => new Promise((resolve,reject)=>{
  //链库
  open({
    dbName,collectionName
  }).then(
    ({collection,client})=>{


      if(!_id || _id.length!==24){
        reject({
          err:1,msg:'id未传，或者格式有误'
        })
        client.close()
        return;
      }

      //查详情

      collection.find({
        _id: ObjectId(_id)
      }).toArray((err,result)=>{
        if(!err && result.length>0){
          resolve({
            err:0,
            msg:'成功',
            data: result[0]
          })
        }else{
          resolve({
            err:0,
            msg:'没有数据'
          })
        }
        client.close();//管库
      })

    }
  ).catch(
    ({err,client}) => {
      reject({
        err:1,
        msg:'库链接失败'
      });
      client.close()
    }
  )
})

exports.open=open;
exports.findList=findList;
exports.findDetail=findDetail;